// pages/user/myOrder/myOrder.js
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		dataType: 'all',
		page: 1,
		hasMore: true,
		data: []
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		this.onPullDownRefresh();

		// 增加订单被评价监听器
		wx.emitter.on('order.evaluate', this.onOrderEvaluate);
	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {
		// 移除订单被评价监听器
		wx.emitter.off('order.evaluate', this.onOrderEvaluate);
	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {
		this.loadData(1).finally(() => {
			wx.stopPullDownRefresh();
		});
	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {
		if (!this.data.hasMore) return;

		const page = this.data.page + 1;
		this.loadData(page);
	},

	// 加载数据列表
	loadData: function(page) {
		if ('refund' === this.data.dataType) {
			return this.loadRefundOrderData(page);
		} else {
			return this.loadOrderData(page);
		}
	},

	// 加载订单列表
	loadOrderData: function(page) {
		return wx.http.post('api/user.order/lists', {
			page: page,
			dataType: this.data.dataType,
		}).then((res) => {
			res = res.data.data.list;
			const hasMore = res.data.length >= res.per_page;

			// 其他特殊计算
			res.data.forEach(it => {
				let goodsTotalPrice = wx.BigNumber('0.00');
				it.goods.forEach(goods => {
					goodsTotalPrice = goodsTotalPrice.plus(goods.total_price);
					goods.discount_price = wx.BigNumber(goods.total_price).minus(goods.total_pay_price).toFixed(2, wx.BigNumber.ROUND_DOWN);
					if (!res.data.is_refunded && goods.refund) {
						res.data.is_refunded = 1;
					}
				});
				it.goods_total_price = goodsTotalPrice.toFixed(2, wx.BigNumber.ROUND_DOWN);
			});
			const orderList = page > 1 ? this.data.data.concat(res.data) : res.data;

			this.setData({
				page: page,
				hasMore: hasMore,
				data: orderList,
			});

			return res.data;
		}, (err) => {
			console.warn("api/user.order/lists", err)
		});
	},

	// 加载退款订单列表
	loadRefundOrderData: function(page) {
		return wx.http.post('api/user.refund/lists', {
			page: page,
			dataType: this.data.dataType,
		}).then((res) => {
			res = res.data.data.list;
			const hasMore = res.data.length >= res.per_page;

			const orderList = page > 1 ? this.data.data.concat(res.data) : res.data;
			this.setData({
				page: page,
				hasMore: hasMore,
				data: orderList,
			});

			return res.data;
		}, (err) => {
			console.warn("api/user.refund/lists", err)
		});
	},

	// tab 切换
	tabItemTap: function(e) {
		const type = e.currentTarget.dataset.type;
		this.data.dataType = type;
		this.setData({
			dataType: type
		});

		this.loadData(1);
	},

	// 取消订单
	cancelOrderTap: function(e) {
		const index = e.currentTarget.dataset.index;
		const item = this.data.data[index];

		wx.showModal({
			content: '取消后将不能恢复，你确定要取消订单吗？',
			showCancel: true,
			success: (res) => {
				if (res.cancel) return;
				wx.http.post('api/user.order/cancel', {
					order_id: item.order_id
				}, {
					showLoading: true
				}).then((res) => {
					const orderStatusTextKey = `data[${index}].state_text`;
					const orderStatusKey = `data[${index}].order_status`;

					this.setData({
						[orderStatusTextKey]: "已取消",
						[orderStatusKey]: {
							"text": "已取消",
							"value": 20
						}
					});
					wx.showToast({
						title: '已取消！'
					});
				});
			}
		});
	},

	// 跳转订单详情
	toOrderTap: function(e) {
		const dataset = e.currentTarget.dataset,
			orderId = dataset.orderId,
			refundId = dataset.refundId;
		if (refundId) {
			wx.navigateTo({
				url: `/pages/user/order/detail/detail?refund_id=${refundId}`
			})
		} else {
			wx.navigateTo({
				url: `/pages/user/order/detail/detail?id=${orderId}`
			})
		}
	},

	// 去支付
	payOrderTap: function(e) {
		const index = e.currentTarget.dataset.index;
		const item = this.data.data[index];
		return wx.http.post('api/user.order/pay', {
			order_id: item.order_id
		}, {
			showLoading: true
		}).then((res) => {
			const payInfo = res.data.data.payment;
			return wx.promise.requestPayment({
				timeStamp: payInfo.timeStamp,
				nonceStr: payInfo.nonceStr,
				package: 'prepay_id=' + payInfo.prepay_id,
				signType: 'MD5',
				paySign: payInfo.paySign,
			});
		}).then((res) => {
			wx.navigateTo({
				url: '/pages/user/order/pay-success/pay-success?order_id=' + item.order_id
			})
		}, () => {
			wx.showToast({
				title: '支付失败！',
				icon: 'none'
			})
		});
	},

	// 确认收货
	receiptTap: function(e) {
		const index = e.currentTarget.dataset.index;
		const item = this.data.data[index];

		wx.showModal({
			content: '你将确认订单，是否继续？',
			showCancel: true,
			success: (res) => {
				if (res.cancel) return;
				wx.http.post('api/user.order/receipt', {
					order_id: item.order_id
				}, {
					showLoading: true
				}).then((res) => {
					const orderStatusTextKey = `data[${index}].state_text`;
					const orderStatusKey = `data[${index}].order_status`;
					this.setData({
						[orderStatusTextKey]: "已收货",
						[orderStatusKey]: {
							"text": "已收货",
							"value": 20
						}
					});
					wx.showToast({
						title: '已收货！'
					});
					wx.navigateTo({
						url: '/pages/user/order/evaluate/evaluate?id=' + item.order_id
					})
				});
			}
		});
	},

	// 订单已被评价
	onOrderEvaluate: function(orderId) {
		orderId = parseInt(orderId);
		const index = this.data.data.findIndex(it => it.order_id === orderId);
		if (index === -1) return;

		const isCommentKey = `data[${index}].is_comment`;
		const orderStatusKey = `data[${index}].order_status`;
		this.setData({
			[isCommentKey]: 1,
			[orderStatusKey]: {
				text: "已完成",
				value: 30
			}
		});
	}
});
